package guava;

import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.cache.CacheLoader;
import org.junit.Test;

import java.text.SimpleDateFormat;
import java.util.Date;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * CacheLoader：
 * User: Realfighter
 * Date: 2014/12/6
 * Time: 10:26
 */
public class CacheLoaderTest {

    @Test
    public void testCacheLoaderFunction() throws Exception {
        Function<Date, String> function = new Function<Date, String>() {
            @Override
            public String apply(Date input) {
                return new SimpleDateFormat("yyyy-MM-dd").format(input);
            }
        };
        CacheLoader<Date, String> cacheLoader = CacheLoader.from(function);

        assertThat(cacheLoader.load(new Date()), is("2014-12-06"));

    }

    @Test
         public void testCacheLoaderSupplier() throws Exception {
        Supplier<Long> supplier = new Supplier<Long>() {
            @Override
            public Long get() {
                //这里简单的返回时间戳
                return System.currentTimeMillis();
            }
        };
        CacheLoader<Object, Long> cacheLoader = CacheLoader.from(supplier);
        System.out.println(cacheLoader.load("first"));
        Thread.sleep(300);//这里线程休息下，方便测试
        System.out.println(cacheLoader.load("second"));
    }

}
